package com.bjpowernode.money.web;

import com.alibaba.dubbo.config.annotation.Reference;
import com.bjpowernode.money.Constant;
import com.bjpowernode.money.Result;
import com.bjpowernode.money.model.LoanInfo;
import com.bjpowernode.money.model.User;
import com.bjpowernode.money.service.BidInfoService;
import com.bjpowernode.money.service.LoanInfoService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/*
    投资功能的实现
 */
@Controller
public class BidInfoController {

    @Reference(interfaceClass = LoanInfoService.class,version = "1.0.0",timeout = 20000)
    LoanInfoService loanInfoService;

    @Reference(interfaceClass = BidInfoService.class,version = "1.0.0",timeout = 20000)
    BidInfoService bidInfoService;

    @RequestMapping("/loan/page/invest")
    @ResponseBody
    public Object invest(@RequestParam(name = "loanId",required = true) Integer loanId,
                         @RequestParam(name = "bidMoney",required = true) Double bidMoney,
                         HttpServletRequest request){

        //基本数据验证 还有再验证一边，对bidMoney的数据再验证一次

        //验证是否登录
        User user = (User) request.getSession().getAttribute(Constant.LOGIN_USER);
        if(!ObjectUtils.allNotNull(user)){
            //说明没有登录
            return Result.error(-1,"请先登录");
        }

        //验证：是否实名认证
        if(!ObjectUtils.allNotNull(user.getName(),user.getIdCard())){
            return Result.error(-2,"请先实名认证");
        }

        //验证：基础数据（课后完成）

        //验证：业务数据（课后完成）
        LoanInfo loanInfo = loanInfoService.queryLoanInfoById(loanId);
//        if(loanInfo.getLeftProductMoney()<bidMoney){
//            return Result.error(0,"您的投资超过了剩余可投金额");
//        }

        //验证：账户余额（不需要验证）

        //投资
        Map<String,Object> parasMap=new HashMap();
        parasMap.put("loanId",loanId);
        parasMap.put("bidMoney",bidMoney);
        parasMap.put("userId",user.getId());
        String tag = null ;

        try {
            tag = bidInfoService.invest(parasMap);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(0,"系统异常");
        }
        if(StringUtils.equals(Constant.BID_FINANCE_MONEY_NOT_MUCH,tag)){
            return Result.error(0,"您的账户余额不足");
        }
        if(StringUtils.equals(Constant.BID_LOAN_LEFT_MONEY_NOT_MUCH,tag)){
            return Result.error(0,"您的投资超过了剩余可投金额");
        }
        if(StringUtils.equals(Constant.BID_BID_INFO_ERROR,tag)){
            return Result.error(0,"投资失败");
        }if(StringUtils.equals(Constant.BID_BID_INFO_SUCCESS,tag)){
            return Result.success("投资成功");
        }

        return null;
    }


}
